package com.fmsz.xmly.adapters.classify;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Rect;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.fmsz.xmly.R;
import com.fmsz.xmly.callbacks.FindClassifyImageHttpService;
import com.fmsz.xmly.entitys.classify.FindClassifyImageEntity;
import com.fmsz.xmly.entitys.classify.FindClassifyListEntity;
import com.squareup.picasso.Picasso;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by Administrator on 2016/12/2.
 */

public class FindClassifyAdapter extends RecyclerView.Adapter<FindClassifyAdapter.ViewHolder> implements Callback<FindClassifyImageEntity>, ViewPager.OnPageChangeListener {


    private Context context;
    private List<FindClassifyListEntity> datas;
    private View headView;
    private View footView;
    private static final String TAG = "FindClassifyAdapter";
    private RecyclerView recycleView;
    private ViewPager pager;
    private int curPosition;
    private final int TIME_UP = 1;
    private boolean isTouch = true;
    private Thread cycleThread;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case TIME_UP:
                    pager.setCurrentItem(++curPosition, true);
                    break;
            }
            super.handleMessage(msg);
        }
    };
    private ImageView[] images;

    public FindClassifyAdapter(Context context) {
        this.context = context;
        datas = new ArrayList<>();
    }

    @Override
    public int getItemViewType(int position) {
        if (headView != null && position == 0) {
            return R.layout.find_classify_head;
        } else if (footView != null && position == datas.size()) {
            return R.layout.find_classify_foot;
        }
        return R.layout.find_classify_normal;
    }

    //添加数据并刷新
    public void addAll(Collection<? extends FindClassifyListEntity> collection) {
        int size = datas.size();
        datas.addAll(collection);
        notifyItemRangeInserted(size + 1, collection.size());
        loadViewPager();
    }

    //设置头布局
    public void setHeadView(View headView) {
        this.headView = headView;
        notifyItemInserted(0);
    }

    private void loadViewPager() {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://adse.ximalaya.com/")
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        FindClassifyImageHttpService service = retrofit.create(FindClassifyImageHttpService.class);
        service.getImageUrl("4.3.98").enqueue(this);
    }

    //设置尾视图
    public void setFootView(View view) {
        this.footView = view;
        pager = ((ViewPager) view.findViewById(R.id.find_classify_view_pager));
        notifyItemInserted(datas.size());
    }

    @Override
    public void onAttachedToRecyclerView(RecyclerView recyclerView) {
        super.onAttachedToRecyclerView(recyclerView);
        this.recycleView = recyclerView;
        GridLayoutManager manager = (GridLayoutManager) this.recycleView.getLayoutManager();
        //设置recycleView的列数
        manager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
            @Override
            public int getSpanSize(int position) {
                if (position == 0 || position == datas.size()) {
                    return 2;
                }
                return 1;
            }
        });
        //设置item之间的偏移量
        RecyclerView.ItemDecoration decoration = new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
                super.getItemOffsets(outRect, view, parent, state);
                int position = parent.getChildAdapterPosition(view);
                if ((position + 1) % 6 == 0 || position % 6 == 0) {
                    outRect.set(0, 0, 1, 30);
                    return;
                }
                outRect.set(0, 0, 1, 1);
            }

            @Override
            public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
                super.onDraw(c, parent, state);
            }

            @Override
            public void onDrawOver(Canvas c, RecyclerView parent, RecyclerView.State state) {
                super.onDrawOver(c, parent, state);
            }
        };
        this.recycleView.addItemDecoration(decoration);
    }

    @Override
    public void onDetachedFromRecyclerView(RecyclerView recyclerView) {
        super.onDetachedFromRecyclerView(recyclerView);
        this.recycleView = null;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        if (headView != null && viewType == R.layout.find_classify_head) {
            return new ViewHolder(headView);
        } else if (footView != null && viewType == R.layout.find_classify_foot) {
            return new ViewHolder(footView);
        }
        return new ViewHolder(LayoutInflater.from(context).inflate(viewType, parent, false));
    }

    @Override
    public void onBindViewHolder(final ViewHolder holder, int position) {
        if (headView != null && getItemViewType(position) == R.layout.find_classify_normal) {
            String iconUrl = datas.get(position).getCoverPath();
            Picasso.with(context).load(iconUrl).into(holder.icon);
            holder.text.setText(datas.get(position).getTitle());
        } else if (headView != null && getItemViewType(position) == R.layout.find_classify_head) {
            Picasso.with(context).load(datas.get(0).getCoverPath()).into(holder.headImage);
        }
    }

    @Override
    public int getItemCount() {
        return footView == null ? datas.size() : datas.size() + 1;
    }

    //分类底部viewpager图片Url下载的回调接口
    @Override
    public void onResponse(Call<FindClassifyImageEntity> call, Response<FindClassifyImageEntity> response) {
        List<FindClassifyImageEntity.DataEntity> dataEntities = response.body().getData();
        images = new ImageView[dataEntities.size() + 2];
        String[] imageUrls = new String[images.length + 2];
        for (int i = 0; i < dataEntities.size(); i++) {
            ImageView imageView = new ImageView(context);
            images[i + 1] = imageView;
            imageUrls[i + 1] = dataEntities.get(i).getCover();
        }
        images[images.length - 1] = new ImageView(context);
        images[images.length - 1].setBackgroundColor(Color.RED);
        images[0] = new ImageView(context);
        imageUrls[0] = dataEntities.get(dataEntities.size() - 1).getCover();
        imageUrls[4] = dataEntities.get(0).getCover();
        FindClassifyPagerAdapter adapter = new FindClassifyPagerAdapter(context, images, imageUrls);
        pager.setAdapter(adapter);
        pager.setCurrentItem(1, false);
        startCycleThread();
        pager.addOnPageChangeListener(this);
//        pager.setOnTouchListener(this);

    }

    private void startCycleThread() {
        cycleThread = new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    Log.i(TAG, "run: " + isTouch);
                    try {
                        Thread.sleep(3 * 1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    Message message = new Message();
                    message.what = TIME_UP;
                    handler.sendEmptyMessage(message.what);
                }
            }
        });
        cycleThread.start();
    }

    @Override
    public void onFailure(Call<FindClassifyImageEntity> call, Throwable t) {
        t.printStackTrace();
        Toast.makeText(context, t.getMessage(), Toast.LENGTH_SHORT).show();
    }

    //ViewPager的滑动监听
    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        curPosition = position;
    }

    @Override
    public void onPageScrollStateChanged(int state) {
        switch (state) {
            case ViewPager.SCROLL_STATE_IDLE:
                if (curPosition == 0) {
                    pager.setCurrentItem(images.length - 2, false);
                } else if (curPosition == images.length - 1) {
                    pager.setCurrentItem(1, false);
                }
                break;
        }
    }

//    @Override
//    public boolean onTouch(View v, MotionEvent event) {
//        switch (event.getAction()) {
//            case MotionEvent.ACTION_DOWN:
//                synchronized (context) {
//                    try {
//                        context.wait();
//                    } catch (InterruptedException e) {
//                        e.printStackTrace();
//                    }
//                }
//                break;
//            case MotionEvent.ACTION_UP:
//            case MotionEvent.ACTION_CANCEL:
//                context.notifyAll();
//                isTouch = true;
//                break;
//        }
//        return false;
//    }


    public static class ViewHolder extends RecyclerView.ViewHolder {
        private final ImageView icon;
        private final TextView text;
        private final ImageView headImage;

        public ViewHolder(View itemView) {
            super(itemView);
            icon = ((ImageView) itemView.findViewById(R.id.find_classify_icon));
            text = ((TextView) itemView.findViewById(R.id.find_classify_text));
            headImage = ((ImageView) itemView.findViewById(R.id.find_classify_head));
        }
    }
}
